package operate

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"handler/runner"
	"io/ioutil"
	"net/http"
	"os"
)

type BuilderRecord struct {
	RunStep string `json:"run_step"`
	Message string `json:"message"`
	Error   string `json:"error"`
	Sha     string `json:"sha"`
	Refname string `json:"refname"`
	Creator string `json:"creator"`
}

func LoginFaas(openfaasPwd string) error {
	args := map[string]string{
		"OPENFAAS_PWD": openfaasPwd,
	}
	err := runner.FaasLogin.Invoke(".", args)
	return err
}

func CloneCode(tag, remoteUrl string) error {
	args := map[string]string{
		"TAG":        tag,
		"REMOTE_URL": remoteUrl,
	}
	err := runner.GitClone.Invoke(".", args)
	return err
}

func BuildCode(projectName, buildFileYml string) error {
	args := map[string]string{
		"BUILD_FILE_YML": buildFileYml,
	}
	err := runner.FaasBuild.Invoke("./"+projectName, args)
	return err
}

func LoginDocker(dockerHost, dockerHubPwd, dockerHubUser string) error {
	args := map[string]string{
		"DOCKER_HOST":     dockerHost,
		"DOCKER_HUB_PWD":  dockerHubPwd,
		"DOCKER_HUB_USER": dockerHubUser,
	}
	err := runner.LoginDocker.Invoke(".", args)
	return err
}

func PushImage(dockerHost, imageName string) error {
	tag := os.Getenv("TAG")
	args := map[string]string{
		"DOCKER_HOST": dockerHost,
		"IMAGE_NAME":  imageName,
		"TAG":         tag,
	}
	err := runner.DockerPush.Invoke(".", args)
	return err
}

func DeployImage(projectName, openfaasPwd, buildFileYml string) error {
	args := map[string]string{
		"OPENFAAS_PWD":   openfaasPwd,
		"BUILD_FILE_YML": buildFileYml,
	}
	err := runner.FaasDeploy.Invoke("./"+projectName, args)
	return err
}

func RecordProcess(step, message, checkoutSha, userName, tag string, err error) error {
	builderRecord := new(BuilderRecord)
	builderRecord.RunStep = step
	builderRecord.Sha = checkoutSha
	builderRecord.Refname = tag
	if err != nil {
		builderRecord.Error = err.Error()
	}
	builderRecord.Creator = userName
	builderRecord.Message = message

	apiServerUrl := os.Getenv("API_SERVER_HOST")
	if apiServerUrl == "" {
		apiServerUrl = "http://192.168.1.108:8088/function/xmysql-ci-runner"
	}
	url := fmt.Sprintf("%s/api/builder_record", apiServerUrl)
	jsonStr, _ := json.Marshal(builderRecord)
	resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonStr))
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	_, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		return errors.New("process task info is wrong")
	}
	return nil
}
